using UnityEngine;
using Unity.Mathematics;
using Buildin.Components;
using Buildin.Utilities;
using Registry;
using Random = UnityEngine.Random;

public class PaintController : MonoBehaviour
{
    [Header("染色配置")]
    public string paintColorHex = "#6aa9ff"; // 小球染色颜色
    public string defaultColorHex = "#282a2e"; // 默认颜色（灰色）
    
    [SerializeField]
    private Color defaultColor;
    public Color DefaultColor
    {
        get
        {
            if (ColorUtility.TryParseHtmlString(defaultColorHex, out var color))
            {
                defaultColor = color;
                return color;
            }
            return Color.black;
        }
    }
    [SerializeField]
    private Color paintColor;
    public Color PaintColor
    {
        get
        {
            if (ColorUtility.TryParseHtmlString(paintColorHex, out var color))
            {
                paintColor = color;
                return color;
            }
            return Color.white;
        }
    }

    // 网格数据
    private Mesh _mesh;
    private MeshRenderer _meshRenderer;
    private MeshFilter _meshFilter;
    private Material _material;
    
    // 缓冲区
    private Vector3[] _positions;
    private Color[] _colors;
    private Vector2[] _uvs;
    private int[] _indices;

    private void Start()
    {
        // 创建大网格
        CreateMesh();
    }

    private void Update()
    {
        ProcessBallPaint();
    }

    private void CreateMesh()
    {
        // 计算网格大小
        var mgr = GameManager.Instance;
        var cellSize = mgr.Grid.CellSize;
        
        // 创建网格组件
        _meshRenderer = gameObject.AddComponent<MeshRenderer>();
        _meshFilter = gameObject.AddComponent<MeshFilter>();
        _mesh = new Mesh();
        _meshFilter.mesh = _mesh;
        
        // 创建材质
        _material = Resources.Load<Material>("PaintMaterial");
        _material.color = Color.white;
        _material.renderQueue += 1;
        _meshRenderer.material = _material;
        
        // 初始化缓冲区 - 为每个网格的4个顶点都创建独立的渲染单元
        var totalCellsCount = mgr.Grid.CellCount.x * mgr.Grid.CellCount.y;
        var totalVertices = totalCellsCount * 4 * 4; // 每个格子4个顶点，每个顶点4个顶点（形成一个四边形）
        var totalIndices = totalCellsCount * 4 * 6; // 每个格子4个顶点，每个顶点6个索引（2个三角形）
        
        _positions = new Vector3[totalVertices];
        _colors = new Color[totalVertices];
        _uvs = new Vector2[totalVertices];
        _indices = new int[totalIndices];
        
        // 生成网格数据
        for (var x = 0; x < mgr.Grid.CellCount.x; x++)
        {
            for (var y = 0; y < mgr.Grid.CellCount.y; y++)
            {
                var cellIndex = x + y * mgr.Grid.CellCount.x;

                // 计算格子世界坐标
                var pointX = mgr.bgRect.x + x * mgr.Grid.CellSize.x;
                var pointY = mgr.bgRect.y + y * mgr.Grid.CellSize.y;

                // 为每个格子的4个顶点创建独立的渲染单元
                Vector3[] vertexPositions = new Vector3[]
                {
                    new Vector3(pointX, pointY, 0), // 左下
                    new Vector3(pointX + cellSize.x, pointY, 0), // 右下
                    new Vector3(pointX + cellSize.x, pointY + cellSize.y, 0), // 右上
                    new Vector3(pointX, pointY + cellSize.y, 0) // 左上
                };

                for (int vertexIndex = 0; vertexIndex < 4; vertexIndex++)
                {
                    var baseVertexOffset = (cellIndex * 4 + vertexIndex) * 4;
                    var baseIndexOffset = (cellIndex * 4 + vertexIndex) * 6;

                    // 为每个顶点创建一个小四边形（用于渲染纹理）
                    var centerPos = vertexPositions[vertexIndex];

                    // 添加随机扰动
                    var randomOffset = new Vector3(
                        UnityEngine.Random.Range(-20f, 20f),
                        UnityEngine.Random.Range(-20f, 20f),
                        0
                    );
                    // randomOffset = new Vector3(0, 0, 0);

                    var finalCenterPos = centerPos + randomOffset;
                    var halfSize = mgr.Grid.CellSize.x * 1f; // 每个顶点渲染单元的大小

                    // 设置4个顶点位置（形成一个四边形）
                    _positions[baseVertexOffset + 0] = new Vector3(finalCenterPos.x - halfSize, finalCenterPos.y - halfSize, 0); // 左下
                    _positions[baseVertexOffset + 1] = new Vector3(finalCenterPos.x + halfSize, finalCenterPos.y - halfSize, 0); // 右下
                    _positions[baseVertexOffset + 2] = new Vector3(finalCenterPos.x + halfSize, finalCenterPos.y + halfSize, 0); // 右上
                    _positions[baseVertexOffset + 3] = new Vector3(finalCenterPos.x - halfSize, finalCenterPos.y + halfSize, 0); // 左上

                    // 设置UV
                    _uvs[baseVertexOffset + 0] = new Vector2(0, 0);
                    _uvs[baseVertexOffset + 1] = new Vector2(1, 0);
                    _uvs[baseVertexOffset + 2] = new Vector2(1, 1);
                    _uvs[baseVertexOffset + 3] = new Vector2(0, 1);

                    // 设置索引
                    _indices[baseIndexOffset + 0] = baseVertexOffset + 0;
                    _indices[baseIndexOffset + 1] = baseVertexOffset + 1;
                    _indices[baseIndexOffset + 2] = baseVertexOffset + 2;
                    _indices[baseIndexOffset + 3] = baseVertexOffset + 0;
                    _indices[baseIndexOffset + 4] = baseVertexOffset + 2;
                    _indices[baseIndexOffset + 5] = baseVertexOffset + 3;

                    // 设置默认颜色和旋转信息
                    for (int i = 0; i < 4; i++)
                    {
                        if (x < mgr.Grid.CellCount.x / 2)
                        {
                            _colors[baseVertexOffset + i] = Color.white;
                        }
                        else
                        {
                            _colors[baseVertexOffset + i] = Color.black;
                        }
                    }

                }
            }
        }
        
        // 应用网格数据
        _mesh.vertices = _positions;
        _mesh.colors = _colors;
        _mesh.uv = _uvs;
        _mesh.triangles = _indices;
        _mesh.RecalculateNormals();
    }
    
    public void ProcessBallPaint()
    {
        var mgr = GameManager.Instance;
        
        var archetype = mgr.World.GetArchetype(EArchetypeRegistryID.Ball);
        var entityCount = archetype.EntityCount;
        if (entityCount <= 0) return;
        
        using var areaCompsSlice =
            mgr.World.GetEntityComponentDataMemorySlice<Area2DComponent>(EArchetypeRegistryID.Ball);
        
        // 对每个小球位置进行染色
        for (var eid = 0; eid < entityCount; ++eid)
        {
            var grid = mgr.Grid;
            var cellPos = Utils.GetCoordinates(ref grid, areaCompsSlice[eid].Center);
            var cellIndex = cellPos.x + cellPos.y * grid.CellCount.x;
            
            var gridPos = new float2()
            {
                x = (cellPos.x - grid.CellCount.x / 2) * grid.CellSize.x,
                y = (cellPos.y - grid.CellCount.y / 2) * grid.CellSize.y
            };
            var vertexIndex = 0;
            // if (gridPos is { x: < 0, y: < 0 }) vertexIndex = 0;
            // else if (gridPos is { x: > 0, y: < 0 }) vertexIndex = 1;
            // else if (gridPos is { x: > 0, y: > 0 }) vertexIndex = 2;
            // else if (gridPos is { x: < 0, y: > 0 }) vertexIndex = 3;
            for (vertexIndex = 0; vertexIndex < 4; ++vertexIndex)
            {
                for (var i = 0; i < 4; ++i)
                {
                    _colors[(cellIndex * 4 + vertexIndex) * 4 + i] = PaintColor;
                }
            }
            // 更新网格
            _mesh.SetColors(_colors);
        }
    }
    
    public void UpdateCellColor(int2 cellPos, Color color)
    {
        var mgr = GameManager.Instance;
        var cellIndex = cellPos.x + cellPos.y * mgr.Grid.CellCount.x; 
        
        // 为每个格子的4个顶点都染色（每个顶点有4个渲染顶点）
        for (var vertexIndex = 0; vertexIndex < 4; vertexIndex++)
        {
            var baseVertexOffset = (cellIndex * 4 + vertexIndex) * 4;
            for (var i = 0; i < 4; i++)
            {
                _colors[baseVertexOffset + i] = color;
            }
        }
        // 更新网格
        _mesh.SetColors(_colors);
    }
}